package cn.xorange.commons.system.service.platform.impl;

import cn.xorange.commons.core.basic.service.BaseService;
import cn.xorange.commons.security.utils.SecurityUtils;
import cn.xorange.commons.system.entity.platform.*;
import cn.xorange.commons.system.mapper.platform.*;
import cn.xorange.commons.system.service.platform.ISysProductService;
import cn.xorange.commons.system.service.platform.ISysTenantProductService;
import com.alibaba.fastjson2.JSONArray;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author : yangjian
 * @date : 2021/12/27
 * @description :
 */
@Service
public class SysProductServiceImpl
        extends BaseService<SysProduct, SysProductMapper>
        implements ISysProductService {

    private static final String PRODUCT_ID = "productId";

    @Resource
    SysProductMenuMapper productMenuMapper;
    @Resource
    SysProductCycleMapper productCycleMapper;

    @Override
    public List<SysProduct> getList(SysProduct sysProduct){
        sysProduct.order.asc("productModule","purpose","sort");
        return super.mapper.selectList(sysProduct);
    }

    @Override
    public int getProductMenuNum(Long productId){
        SysProductMenu sysProductMenu = new SysProductMenu();
        sysProductMenu.where.equal(PRODUCT_ID,productId);
        return productMenuMapper.count(sysProductMenu);
    }
    @Override
    public ArrayList<Long> getProductMenuIds(Long productId){
        return mapper.getProductMenuIds(productId);
    }

    @Override
    public List<Long> getProductMenuIds(Set<Long> productIds) {
        SysProductMenu productMenu = new SysProductMenu();
        productMenu.where.in("productId",productIds);
        List<SysProductMenu> menus = productMenuMapper.selectList(productMenu);
        List<Long> ids = new ArrayList<>();
        for(SysProductMenu m : menus){
            ids.add(m.getMenuId());
        }
        return ids;
    }

    @Override
    public void setProductMenus(Long productId, JSONArray menuIds){
        Map<String, Object> fields = new HashMap<>(1);
        fields.put(PRODUCT_ID, productId);
        setRelationIds(fields, menuIds,"menuId", productMenuMapper, SysProductMenu.class);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public int deleteById(Long productId){

        SysProductMenu sysProductMenu = new SysProductMenu();
        sysProductMenu.setProductId(productId);
        productMenuMapper.del(sysProductMenu);

        SysProductCycle productCycle = new SysProductCycle();
        productCycle.setProductId(productId);
        productCycleMapper.del(productCycle);

        return super.deleteById(productId);

    }
}
